<template>
  <div>
    <!--面包屑导航区-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片视图区域-->
    <el-card >
      <!--添加区域-->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible=true" >添加角色</el-button>
        </el-col>
      </el-row>
      <!--角色列表区域-->
      <el-table :data="roleList" border stripe >
        <!--展开列-->
        <el-table-column type="expand">
          <template slot-scope="permission">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop':'','vcenter']" v-for="(item1,i1) in permission.row.child" v-bind:key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(permission.row,item1.id)">{{item1.name}}</el-tag><i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级、三级权限 -->
              <el-col :span="19">
                <!--通过 for 循环嵌套渲染二级权限-->
                <el-row :class="[i2 === 0 ? '':'bdtop','vcenter']" v-for="(item2,i2) in item1.child" v-bind:key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightsById(permission.row,item2.id)">{{item2.name}}</el-tag><i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.child" v-bind:key="item3.id" closable @close="removeRightsById(permission.row,item3.id)">{{item3.name}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!--索引列-->
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="name"></el-table-column>
        <el-table-column label="角色描述" prop="description"></el-table-column>
        <el-table-column label="创建时间" prop="createTime"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="joy">
            <!--修改按钮-->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(joy.row.id)">编辑</el-button>
            <!--删除按钮-->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeRoleById(joy.row.id)">删除</el-button>
            <!--分配权限角色-->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(joy.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!--添加角色对话框-->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      width="50%" @close="addDialogClosed">
      <!--内容主体区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="角色名" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="addForm.description"></el-input>
        </el-form-item>
      </el-form>
      <!--底部区域-->
      <span slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addRole">确 定</el-button>
  </span>
    </el-dialog>
    <!--编辑角色对话框-->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="角色名" prop="name">
          <el-input v-model="editForm.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="说明" prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editRoleInfo">确 定</el-button>
  </span>
    </el-dialog>
    <!--分配权限的对话框-->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%" @close="setRightDialogClosed">
      <!--树形控件-->
      <el-tree :data="rightsTreeList" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defKeys" ref="treeRef" ></el-tree>
      <span slot="footer" class="dialog-footer">
    <el-button @click="setRightDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="allotRights">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色列表
      roleList: [],
      // 控制添加角色对话框的显示与隐藏
      addDialogVisible: false,
      // 角色添加表单
      addForm: {
        name: '',
        description: ''
      },
      // 添加角色表单的验证规则对象
      addFormRules: {
        name: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 10, message: '角色名长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 控制修改角色对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的角色对象
      editForm: {},
      editFormRules: {
        name: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 10, message: '角色名长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据,方便树形控件使用
      rightsTreeList: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'name',
        children: 'child'
      },
      // 默认选中的节点id值数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: '',
      fenCan: {
        ids: ''
      }
    }
  },
  created() {
    // 获取所有的角色
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const result = await this.$http.get('/role/roles')
      if (result.data.data.code !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = result.data.data.data
    },
    // 监听添加角色对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新角色
    addRole() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false
        // 可以添加角色的网络请求
        const result = await this.$http.post('/role/save', this.addForm)
        if (result.data.code !== 200) {
          this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        // 隐藏添加用户的对话框
        this.addDialogVisible = false
        // 刷新列表
        this.getRoleList()
      })
    },
    // 展示编辑角色的对话框
    async showEditDialog(id) {
      const result = await this.$http.get('/role/getRole/' + id)
      if (result.data.code !== 200) {
        return this.$message.error('查询角色信息失败')
      }
      this.editForm = result.data.data
      // 显示对话框
      this.editDialogVisible = true
    },
    // 监听修改角色对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改角色信息的表单提交
    editRoleInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false
        // 发起修改用户的数据请求
        const result = await this.$http.put('/role/updateRole/' + this.editForm.id, {
          description: this.editForm.description
        })
        if (result.data.code !== 200) {
          return this.$message.error('角色信息更新失败！')
        }
        // 关闭对话框
        this.editDialogVisible = false
        // 刷新列表
        this.getRoleList()
        // 提示成功
        return this.$message.success('角色信息更新成功！')
      })
    },
    // 根据id删除对应的角色信息
    async removeRoleById(id) {
      // 弹框询问是否删除用户
      const result = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，则返回字符串 confirm
      // 如果用户取消删除，则返回字符串 cancel
      if (result !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const res = await this.$http.delete('/role/delete/' + id)
      if (res.data.code !== 200) {
        return this.$message.error('删除角色失败！')
      }
      this.$message.success('删除角色成功！')
      this.getRoleList()
    },
    // 根据id删除对应的权限
    async removeRightsById(role, pid) {
      // 弹框提示是否删除权限
      const result = await this.$confirm('此操作将永久解除角色该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果用户确认删除，则返回字符串 confirm
      // 如果用户取消删除，则返回字符串 cancel
      if (result !== 'confirm') {
        return this.$message.info('已取消解绑')
      }
      const res = await this.$http.delete(`/role/${role.id}/permission/${pid}`)
      if (res.data.code !== 200) {
        return this.$message.error('解绑权限失败！')
      }
      role.child = res.data.data
    },
    // 展示分配权限的对话框
    async showSetRightDialog(role) {
      this.roleId = role.id
      // 获取所有权限的数据
      const result = await this.$http.get('/permission/getAllMenu')
      if (result.data.code !== 200) {
        return this.$message.error('获取权限数据失败！')
      }
      // 把获取到的权限数据保存在data中
      this.rightsTreeList = result.data.data
      // 递归获取角色下所有三级权限的id
      this.getLeafKeys(role, this.defKeys)
      this.setRightDialogVisible = true
    },
    // 通过递归的形式，获取角色下所有三级权限的id,并保存到 defKeys 数组中
    getLeafKeys(node, arr) {
      // 检查该节点上是否有child属性判断是否为三级权限<由于后端对三级权限没有去掉child属性，此处还对权限等级进行判断，防止将角色id错误绑定到三级权限节点>
      if (node.child.length < 1 && node.level === 3) {
        return arr.push(node.id)
      }
      node.child.forEach(item =>
        this.getLeafKeys(item, arr)
      )
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      // 拿到半选和全选的权限id
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const ids = keys.join(',')
      const result = await this.$http.post(`/role/updatePermission/${this.roleId} `, { ids: ids })
      if (result.data.code !== 200) {
        return this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this.getRoleList()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eee;
}
.bdbottom{
  border-bottom: 1px solid #eee;
}
.vcenter{
  display: flex;
  align-items: center;
}
</style>
